// 搜索请求数据逻辑
import {CombatScriptDocument, ESSearchResponse, SCRIPT_TYPES, SEARCH_TYPES} from './CombatScriptRepDO'
import axios, { AxiosResponse } from 'axios'
import { ES_CONFIG } from '@/config/elasticsearch'


// ES查询构建函数
export const buildESQuery = (searchType: number, searchQuery: string, selectedType?: string) => {
  const query = {
    bool: {
      must: [] as any[]
    }
  }

  // 添加类型过滤
  if (selectedType) {
    query.bool.must.push({
      term: {
        "type_str.keyword": selectedType
      }
    })
  }

  // 添加搜索条件
  searchQuery = searchQuery.trim()
  if (searchQuery) {
    switch (searchType) {
      case SEARCH_TYPES.FUZZY:
        query.bool.must.push({
          match: {
            desc: {
              query: searchQuery,
              fuzziness: 'AUTO'
            }
          }
        })
        break

      case SEARCH_TYPES.CONTRAIN:
        const keywords = searchQuery.split(/\s+/)
        query.bool.must.push(...keywords.map(keyword => ({
          match_phrase: {
            desc: {
              query: keyword
            }
          }
        })))
        break

      case SEARCH_TYPES.SEQ_CONTRAIN:
        query.bool.must.push({
          match_phrase: {
            desc: {
              query: searchQuery,
              slop: 15
            }
          }
        })
        break

      case SEARCH_TYPES.MATCH_ID:
        query.bool.must.push({
          bool: {
            must: [
              { term: { id: parseInt(searchQuery) } },
              selectedType ? { term: { "type_str.keyword": selectedType } } : undefined
            ].filter(Boolean)
          }
        })
        break
    }
  }

  return query
}

// 添加 ES 请求函数
export const esSearchScripts = async (query: any, from: number, size: number, sort?: Array<Record<string, "asc" | "desc">>) => {
    console.log('Sending request to ES:', `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_search`);
    const requestBody = {
        track_total_hits: true,
        from,
        size,
        query,
        ...(sort && { sort })
    }
    console.log('Request payload:', requestBody);

    try {
        const response = await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_search`,
            requestBody,
            {
                withCredentials: true,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            }
        );
        console.log('ES response:', response);
        return response;
    } catch (error) {
        console.error('ES request failed:', error);
        throw error;
    }
}

// /**
//  * 更新索引映射，设置id为数字类型
//  */
// export const updateMapping = async () => {
//     try {
//         // 先删除旧索引
//         await axios.delete(
//             `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}`,
//             {
//                 withCredentials: false,
//                 headers: {
//                     'Content-Type': 'application/json'
//                 }
//             }
//         )

//         // 创建新索引并设置映射
//         await axios.put(
//             `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}`,
//             {
//                 mappings: {
//                     properties: {
//                         id: {
//                             type: "long"  // 使用长整型
//                         },
//                         type_str: {
//                             type: "keyword"  // 使用keyword类型以支持精确匹配和聚合
//                         },
//                         desc: {
//                             type: "text",  // 使用text类型以支持全文搜索
//                             fields: {
//                                 keyword: {
//                                     type: "keyword",
//                                     ignore_above: 256
//                                 }
//                             }
//                         },
//                         note: {
//                             type: "text",
//                             fields: {
//                                 keyword: {
//                                     type: "keyword",
//                                     ignore_above: 256
//                                 }
//                             }
//                         }
//                     }
//                 }
//             },
//             {
//                 withCredentials: false,
//                 headers: {
//                     'Content-Type': 'application/json'
//                 }
//             }
//         )

//         return true
//     } catch (error) {
//         console.error('Failed to update mapping:', error)
//         throw error
//     }
// }

/**
 * 获取指定类型的最大ID
 */
export const esGetMaxId = async (type_str: string): Promise<number> => {
    try {
        const response = await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_search`,
            {
                size: 1,
                query: {
                    bool: {
                        must: [
                            { term: { "type_str.keyword": type_str } }
                        ]
                    }
                },
                sort: [
                    {
                        "id": "desc"  // 现在id是数字类型，可以直接排序
                    }
                ]
            },
            {
                withCredentials: false,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            }
        )

        const data = response.data as ESSearchResponse<CombatScriptDocument>
        if (data.hits.total.value === 0) {
            return 0
        }

        return data.hits.hits[0]._source.id
    } catch (error) {
        console.error('Failed to get max id:', error)
        throw error
    }
}

// 修改 esAddScript 的参数类型，确保 id 不能为 null
export interface AddScriptPayload {
    id: number  // 改为必填的 number 类型
    type_str: string
    desc: string
    note?: string
}

export const esAddScript = async (script: AddScriptPayload): Promise<AxiosResponse> => {
    try {
        // 先检查是否存在相同 id 和 type 的文档
        const exists = await esCheckScriptExists(script.id, script.type_str)
        if (exists) {
            throw new Error('相同ID和类型的脚本已存在')
        }

        return await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_doc`,
            {
                id: script.id,
                type_str: script.type_str,
                desc: script.desc,
                note: script.note
            },
            {
                withCredentials: false,
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        )
    } catch (error) {
        if (axios.isAxiosError(error)) {
            throw new Error(`添加脚本失败: ${error.response?.data?.error || error.message}`)
        }
        throw error
    }
}

/**
 * 编辑脚本
 */
export const esEditScript = async (script: CombatScriptDocument): Promise<AxiosResponse> => {
    try {
        return await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_update_by_query`,
            {
                query: {
                    bool: {
                        must: [
                            { term: { id: script.id } },
                            { term: { "type_str.keyword": script.type_str } }
                        ]
                    }
                },
                script: {
                    source: "ctx._source.desc = params.desc; ctx._source.note = params.note;",
                    params: {
                        desc: script.desc,
                        note: script.note
                    }
                }
            },
            {
                withCredentials: false,
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        )
    } catch (error) {
        if (axios.isAxiosError(error)) {
            throw new Error(`编辑脚本失败: ${error.response?.data?.error || error.message}`)
        }
        throw error
    }
}

/**
 * 删除脚本
 */
export const esDeleteScript = async (scriptId: number, scriptType: string): Promise<AxiosResponse> => {
    if (!scriptId || !scriptType) {
        throw new Error('scriptId 和 scriptType 都不能为空')
    }

    const requestBody = {
        query: {
            bool: {
                must: [
                    { term: { "id": scriptId } },
                    { term: { "type_str.keyword": scriptType } }
                ]
            }
        },
        conflicts: "proceed"
    }

    try {
        const response = await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_delete_by_query`,
            requestBody,
            {
                withCredentials: false,
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        )

        if (response.data.deleted === 0) {
            throw new Error('未找到要删除的脚本')
        }

        return response
    } catch (error) {
        if (axios.isAxiosError(error)) {
            throw new Error(`删除脚本失败: ${error.response?.data?.error || error.message}`)
        }
        throw error
    }
}

/**
 * 添加脚本前检查是否存在
 */
export const esCheckScriptExists = async (id: number, type: string): Promise<boolean> => {
    try {
        const response = await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_search`,
            {
                query: {
                    bool: {
                        must: [
                            { term: { id: id } },
                            { term: { "type_str.keyword": type } }
                        ]
                    }
                }
            },
            {
                withCredentials: false,
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        )
        return response.data.hits.total.value > 0
    } catch (error) {
        if (axios.isAxiosError(error)) {
            throw new Error(`检查脚本是否存在失败: ${error.response?.data?.error || error.message}`)
        }
        throw error
    }
}

/**
 * 验证文档是否存在
 */
export const esValidateDocument = async (scriptId: number, scriptType: string): Promise<boolean> => {
    try {
        const response = await axios.post(
            `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.scriptDocs}/_search`,
            {
                query: {
                    bool: {
                        must: [
                            { term: { "id": scriptId } },
                            { term: { "type_str.keyword": scriptType } }
                        ]
                    }
                },
                size: 0  // 我们只需要知道是否存在不需要具体文档
            },
            {
                withCredentials: false,
                headers: {
                    'Content-Type': 'application/json'
                }
            }
        )

        return response.data.hits.total.value > 0
    } catch (error) {
        if (axios.isAxiosError(error)) {
            throw new Error(`验证文档失败: ${error.response?.data?.error || error.message}`)
        }
        throw error
    }
}

/**
 * 搜索得到所有的结果返回
 */
export const SearchAllCombatScript = async () => {
  const query = buildESQuery(SEARCH_TYPES.MATCH_ID, '', '')

  const response = await esSearchScripts(query, 0, 9999)
  const data = response.data as ESSearchResponse<CombatScriptDocument>
  const clearData = data.hits.hits.map(hit => ({
      id: hit._source.id,
      desc: hit._source.desc,
      note: hit._source.note,
      type_str: hit._source.type_str,
      score: hit._score
  }))
  return clearData
}
